<template>
  <div id="userRegisterView">
    <h2 style="margin-bottom: 16px">用户注册</h2>
    <a-form
      style="max-width: 480px; margin: 0 auto"
      label-align="left"
      auto-label-width
      :model="form"
      :rules="formRules"
      @submit="handleSubmit"
    >
      <!-- 账号 -->
      <a-form-item field="userAccount" label="账号" required>
        <a-input
          v-model="form.userAccount"
          placeholder="请输入账号（4-16位字母数字组合）"
          allow-clear
        />
      </a-form-item>

      <!-- 密码 -->
      <a-form-item field="userPassword" label="密码" required>
        <a-input-password
          v-model="form.userPassword"
          placeholder="请输入密码（至少8位）"
          allow-clear
        />
      </a-form-item>

      <!-- 确认密码 -->
      <a-form-item field="checkPassword" label="确认密码" required>
        <a-input-password
          v-model="form.checkPassword"
          placeholder="请再次输入密码"
          allow-clear
        />
      </a-form-item>

      <!-- 提交按钮 -->
      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 120px">
          立即注册
        </a-button>
        <a-button
          type="secondary"
          style="margin-left: 16px; width: 120px"
          @click="router.push('/user/login')"
        >
          已有账号？
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { reactive } from "vue";
import { UserControllerService, UserRegisterRequest } from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";

const router = useRouter();

/**
 * 表单数据（与后端接口严格对应）
 */
const form = reactive<UserRegisterRequest>({
  userAccount: "",
  userPassword: "",
  checkPassword: "",
});

/**
 * 表单验证规则
 */
const formRules = {
  userAccount: [
    { required: true, message: "账号不能为空" },
    { minLength: 4, message: "账号长度不能小于4位" },
    { maxLength: 16, message: "账号长度不能超过16位" },
    {
      match: /^[a-zA-Z0-9]+$/,
      message: "账号只能包含字母和数字",
    },
  ],
  userPassword: [
    { required: true, message: "密码不能为空" },
    { minLength: 8, message: "密码长度不能小于8位" },
  ],
  checkPassword: [
    {
      validator: (value: string, cb: any) => {
        if (value !== form.userPassword) {
          cb("两次输入的密码不一致");
        }
      },
    },
  ],
};

/**
 * 提交注册请求
 */
const handleSubmit = async () => {
  try {
    const res = await UserControllerService.userRegisterUsingPost(form);
    console.log(res);

    if (res.code === 0) {
      message.success("注册成功，即将跳转登录");
      setTimeout(() => {
        router.push({
          path: "/user/login",
          query: {
            redirect: router.currentRoute.value.query.redirect,
          },
        });
      }, 1500);
    } else {
      message.error(`注册失败：${res.message}`);
    }
  } catch (error) {
    message.error("请求失败，请检查网络连接");
  }
};
</script>

<style scoped>
#userRegisterView {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}
</style>
